<template>
  <div class="setting">
    <el-card>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- label----tab标签 -->
        <el-tab-pane label="角色管理" name="rols">
          <!-- 添加角色按钮 -->
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="AddingRoles">添加角色</el-button>
          <!-- 表格 -->
          <el-table
            :data="tableData"
            style="width: 100%;margin-top:20px"
            border
          >
            <!-- lable是表格标题 prop是字段属性 -->
            <el-table-column type="index" :index="indexMethod" label="序号" width="120px" />
            <el-table-column label="角色名称" prop="name" />
            <el-table-column label="描述" prop="description" />
            <el-table-column label="操作">
              <template #default="{row}">
                <el-button size="small" type="success" @click="setRole(row.id)">分配权限</el-button>
                <el-button size="small" type="primary" @click="showEdit(row.id)">修改</el-button>
                <el-button size="small" type="danger" @click="delRolet(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页器 -->
          <el-pagination
            :current-page="page"
            :page-sizes="[1, 2, 3, 4]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-tab-pane>
        <el-tab-pane label="公司信息" name="company">
          <!-- 面板 -->
          <el-form label-width="80px">
            <el-form-item label="企业名称" style="width:450px">
              <el-input disabled :value="companyInfo.name" />
            </el-form-item>
            <el-form-item label="公司地址" style="width:450px">
              <el-input disabled :value="companyInfo.companyAddress" />
            </el-form-item>
            <el-form-item label="公司电话" style="width:450px">
              <el-input disabled :value="companyInfo.companyPhone" />
            </el-form-item>
            <el-form-item label="邮箱" style="width:450px">
              <el-input disabled :value="companyInfo.mailbox" />
            </el-form-item>
            <el-form-item label="备注" style="width:450px">
              <el-input disabled :value="companyInfo.remarks" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      v-if="vaisible"
      title="提示"
      :visible="vaisible"
      width="30%"
    >
      <el-form ref="ruleForm" label-width="80px" :model="form" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限的弹层 -->
    <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog">
      <!--  check-strictly 设置不关联 -->
      <el-tree
        ref="treeRef"
        :data="rolesList"
        :props="{'label' :'name'}"
        show-checkbox
        check-strictly
        node-key="id"
      />
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="closeAssignDialog">取消</el-button>
          <el-button type="primary" @click="cliockAll">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { reqGetRolesList, reqDelRole, reqGetCompanyInFo, reqPostRole, reqGetRoleDetail, reqUpdateRole, reqAssignPerm } from '@/api/character'
import { reqGetPermissionList } from '@/api/permisson'
import { reanListToTreeData } from '@/utils/departments'
export default {
  name: 'Setting',
  data() {
    return {
      vaisible: false,
      activeName: 'rols', // 默认激活的tab
      tableData: [], // 表格数据
      total: 0, // 总页数
      page: 1, // 当前页码
      pagesize: 2, // 每页条数,
      companyInfo: [],
      // 表单验证
      form: {
        name: '',
        description: '',
        id: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: ['blur', 'change'] }
        ]
      },
      showAssignDialog: false,
      rolesList: [], // 权限列表数组
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  mounted() {
    console.log(this.$refs.ruleForm)
  },
  methods: {
    handleClick(tab) {
      // 进入第二个面板，且只获取一次
      if (tab.name === 'company' && !this.companyInfo.name) {
        this.getCompanyInFo()
      }
    },
    // 获取所有角色列表
    async getRolesList() {
      const { data: { rows, total }} = await reqGetRolesList(this.page, this.pagesize)
      this.tableData = rows
      this.total = total
    },
    // 每页条数发生变化处理的函数
    handleSizeChange(val) { // 最新页码
      this.pagesize = val
      this.page = 1
      this.getRolesList()
    },
    // 页码发生变化处理的函数
    handleCurrentChange(val) { // 最新条数
      this.page = val
      this.getRolesList()
    },
    // 自定义索引
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 删除角色
    delRolet(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        type: 'warning'
      }).then(async() => {
        await reqDelRole(id)
        // 如果当前的长度为1才让page--
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
        this.getRolesList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 查询企业信息
    async getCompanyInFo() {
      const { data } = await reqGetCompanyInFo(this.$store.state.user.UserInfo.companyId)
      this.companyInfo = data
    },
    // 点击添加角色
    AddingRoles() {
      this.vaisible = true
    },
    // 点击from表单提交
    submitForm() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          // 请求接口
          if (this.form.id === '') {
            await reqPostRole(this.form)
            this.$refs.ruleForm.resetFields()
          } else {
            await reqUpdateRole(this.form)
            this.$refs.ruleForm.resetFields()
          }
          // 重新渲染页面
          this.vaisible = false
          this.getRolesList()
        } else {
          this.$message.info('添加失败，请重新输入')
        }
      })
    },
    // 点击取消
    resetForm() {
      this.vaisible = false
      console.log(this.$refs)
      this.$refs['ruleForm'].resetFields()
    },
    // 点击修改
    async showEdit(id) { // 通过id回显
      // console.log(id)
      const { data } = await reqGetRoleDetail(id)
      // console.log(data)
      this.vaisible = true
      this.form = data
    },
    closeAssignDialog() {
      this.showAssignDialog = false
      this.$refs.treeRef.setCheckedKeys([])
    },
    // 点击分配权限
    async  setRole(id) {
      console.log(id)
      this.showAssignDialog = true
      const { data } = await reqGetPermissionList()// 获取所有权限
      this.rolesList = reanListToTreeData(data, '0')// 转树形
      const { data: data2 } = await reqGetRoleDetail(id)// 基于角色id获取角色详情，角色之前的权限
      console.log(data2)
      this.$refs.treeRef.setCheckedKeys(data2.permIds)
    },
    async cliockAll() {
      await reqAssignPerm({
        id: this.roleId,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      this.showAssignDialog = false
    }

  }

}
</script>

<style>

</style>
